const wxAPI = require('../common/wxAPI');
const requester = require('../common/requester');
const config = require('../common/config');
const setTabBar = require('../utils/setTabBar');
const shareCodeHandler = require('../utils/shareCodeHandler');
const app = getApp();

/**
 * 判断用户之前有过登录操作，如果有则不需要展示授权弹窗
 * @returns {Promise.<TResult>}
 */
const isUserInfoSaved = () => {
    let reqUserObj = {
        url: config.service.userInfo,
        data: {}
    };
    return requester.request(reqUserObj)
        .then(res => {
            let needGetUserInfo = res.data.needGetUserInfo;
            let shareCode = res.data.shareCode;
            app.globalData.isAuthed = needGetUserInfo === 0;
            shareCodeHandler.setMyShareCode(shareCode);
            return needGetUserInfo;
        })
};

/**
 * 判断当前是否处在 audit 状态
 * auditStatus = 0 审核中
 * auditStatus = 1 已审核
 * @returns {Promise.<TResult>}
 */
const getWxAuditStatus = () => {
    let reqObj = {
        url: config.service.getWxAuditStatus,
        data: {
            wxVersion: config.version
        }
    };
    return requester.request(reqObj)
        .then(res => {
            let isAudit = res.data.auditStatus === '0';
            app.globalData.isAudit = isAudit;
            /*if (isAudit) {
                wx.hideTabBar()
            } else {
                setTabBar.showTabBar();
            }*/
            return isAudit;
        });
};

const onLoad = () => {
    wxAPI.getSystemInfo();
    /*检测session状态，如果过期则重新请求wx.login*/
    return wxAPI.checkSession()
        .then(() => {
            let p1 = getWxAuditStatus();
            let p2 = isUserInfoSaved();
            return Promise.all([p1, p2]);
        })
        .then(() => {
            return true;
        })
};

module.exports = onLoad;